/***********************************************
 @Name :        小谭老师
 @Time :        2025-2-22
 @Email :       tan.zhipeng@outlook.com
 @Comment :     功能窗口 天气预报
 @FileName :    widget_funcd_weather.cpp
 @Version :     1.0
************************************************/


#include "widget_funcd_weather.h"
#include "ui_widget_funcd_weather.h"

#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QMessageBox>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QDebug>

Widget_funcD_Weather::Widget_funcD_Weather(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcD_Weather)
{
    ui->setupUi(this);
    
    // 初始化网络管理器和天气信息对象（新增）
       m_netManager = new QNetworkAccessManager(this);
       m_weatherInfo = new WeatherInfo(this);
       
       // 初始化温度曲线控件并添加到widget_3
          m_tempChart = new Weather_lable(this);
          // 设置为widget_3的子控件并充满整个widget_3
          if (ui->widget_3->layout()) {
              delete ui->widget_3->layout(); // 清除现有布局
          }
          QVBoxLayout *layout = new QVBoxLayout(ui->widget_3);
          layout->setContentsMargins(0, 0, 0, 0);
          layout->addWidget(m_tempChart);
          m_tempChart->setStyleSheet("background-color: transparent;"); // 透明背景
          
        
    
    // 将这三个已存在的标签传递给搜索处理器
        m_searchHandler = new city_search_handler(
            ui->lineEdit,    // 输入标签
            ui->label_2,   // 结果显示标签
            ui->label_3,   // 搜索标志标签
            this
        );
       
        // 连接信号槽
            connect(m_searchHandler, &city_search_handler::searchCompleted, 
                    this, &Widget_funcD_Weather::onCitySearchCompleted);
            connect(m_netManager, &QNetworkAccessManager::finished,
                    this, &Widget_funcD_Weather::onWeatherReplyFinished);
            
    ui->label_4->setPixmap(QPixmap(":/多云"));
    ui->label_4->setScaledContents(true);
    ui->label_6->setPixmap(QPixmap(":/湿度"));
    ui->label_6->setScaledContents(true);
    ui->label_12->setPixmap(QPixmap(":/时间"));
    ui->label_12->setScaledContents(true);
    ui->widget_1_icon->setPixmap(QPixmap(":/多云"));
    ui->widget_1_icon->setScaledContents(true);
    ui->widget_2_icon->setPixmap(QPixmap(":/多云"));
    ui->widget_2_icon->setScaledContents(true);
    ui->widget_3_icon->setPixmap(QPixmap(":/多云"));
    ui->widget_3_icon->setScaledContents(true);
    ui->widget_4_icon->setPixmap(QPixmap(":/多云"));
    ui->widget_4_icon->setScaledContents(true);
    ui->widget_5_icon->setPixmap(QPixmap(":/多云"));
    ui->widget_5_icon->setScaledContents(true);
    ui->widget_6_icon->setPixmap(QPixmap(":/多云"));
    ui->widget_6_icon->setScaledContents(true);
    ui->widget_7_icon->setPixmap(QPixmap(":/多云"));
    ui->widget_7_icon->setScaledContents(true);
    ui->label_5->setText("26°C");
    ui->label_7->setText("22");
    ui->label_8->setText("PM2.5:");
    ui->label_9->setText("PM10:");
    ui->label_10->setText("空气质量：");
    ui->label_11->setPixmap(QPixmap(":/风力"));
    ui->label_11->setScaledContents(true);
    fetchWeatherInfo("101250101");

}

Widget_funcD_Weather::~Widget_funcD_Weather()
{
    delete ui;
    delete m_searchHandler;
    delete m_weatherInfo;
    delete m_netManager;  // 新增：释放网络管理器
}

void Widget_funcD_Weather::onCitySearchCompleted()
{
    QString cityId = m_searchHandler->getCityId();
        QString cityName = m_searchHandler->getCityName();
        if (!cityId.isEmpty() && !cityName.isEmpty()) {
            fetchWeatherInfo(cityId);
        } else {
            QMessageBox::information(this, "提示", "请先输入有效的城市名称");
            ui->label_2->setText("未找到城市");
        }
}

void Widget_funcD_Weather::fetchWeatherInfo(const QString &cityId)
{
    // 构建API请求URL
    QString urlStr = QString("http://t.weather.itboy.net/api/weather/city/%1").arg(cityId);
    QUrl url(urlStr);
    QNetworkRequest request(url);
    
    // 设置请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    
    // 发送GET请求
    m_netManager->get(request);
}

void Widget_funcD_Weather::onWeatherReplyFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        QMessageBox::warning(this, "网络错误", "获取天气信息失败：" + reply->errorString());
        reply->deleteLater();
        return;
    }
    
    // 读取响应数据
    QByteArray data = reply->readAll();
    reply->deleteLater();
    
    // 解析JSON数据
    if (m_weatherInfo->loadFromJson(QString(data))) {
        // 解析成功，更新UI
        updateWeatherUI();
    } else {
        QMessageBox::warning(this, "解析错误", "无法解析天气信息数据");
    }
}

void Widget_funcD_Weather::updateWeatherUI()
{
    // 更新基本天气信息（假设UI上有这些标签控件）
    ui->label_2->setText(m_weatherInfo->city());
    ui->label_34->setText(m_weatherInfo->date());
    ui->label_35->setText("更新时间:" + m_weatherInfo->updateTime());
    ui->label_5->setText(m_weatherInfo->wendu() + "°C");
    ui->label_7->setText(m_weatherInfo->shidu());
    ui->label_8->setText(QString("PM2.5: %1").arg(m_weatherInfo->pm25()));
    ui->label_9->setText(QString("PM10: %1").arg(m_weatherInfo->pm10()));
    ui->label_10->setText("空气质量: " + m_weatherInfo->quality());
    ui->label->setText("健康提示: " + m_weatherInfo->ganmao());
    
    // 更新未来7天天气预报
    QList<Forecast> forecasts = m_weatherInfo->forecastList();
    
    // 假设UI中有7个用于显示每日天气的控件组
    for (int i = 0; i < forecasts.size() && i < 7; ++i) {
        Forecast f = forecasts[i];
        
        // 根据实际UI控件名称进行修改
        QLabel *dateLabel = findChild<QLabel*>(QString("widget_%1_week").arg(i+1));
        QLabel *weatherLabel = findChild<QLabel*>(QString("forecastWeather%1").arg(i+1));
        QLabel *tempLabel = findChild<QLabel*>(QString("widget_%1_temp").arg(i+1));
        QLabel *windLabel = findChild<QLabel*>(QString("forecastWind%1").arg(i+1));
        QLabel *iconLabel = findChild<QLabel*>(QString("widget_%1_icon").arg(i+1));
        
        if (dateLabel) dateLabel->setText( f.week);
        if (weatherLabel) weatherLabel->setText(f.type);
        if (tempLabel) tempLabel->setText(f.low +'\n'+ f.high);
        if (windLabel) windLabel->setText(f.fx + " " + f.fl);
        
        // 根据天气类型设置对应图标
        if (iconLabel) {
            if (f.type.contains("晴")) {
                iconLabel->setPixmap(QPixmap(":/晴"));
            } else if (f.type.contains("小雨")) {
                iconLabel->setPixmap(QPixmap(":/小雨"));
            } else if (f.type.contains("阴") || f.type.contains("云")) {
                iconLabel->setPixmap(QPixmap(":/多云"));
            } else if (f.type.contains("大雨") ) {
                iconLabel->setPixmap(QPixmap(":/大雨"));
            }else if (f.type.contains("中雨") ) {
                iconLabel->setPixmap(QPixmap(":/中雨"));
            }else if (f.type.contains("暴雨") ) {
                iconLabel->setPixmap(QPixmap(":/暴雨"));
            }else if (f.type.contains("小雪")) {
                iconLabel->setPixmap(QPixmap(":/小雪"));
            } else if (f.type.contains("暴雪")) {
                iconLabel->setPixmap(QPixmap(":/暴雪"));
            }else if (f.type.contains("雷阵雨")) {
                iconLabel->setPixmap(QPixmap(":/雷阵雨"));
            } else {
                iconLabel->setPixmap(QPixmap(":/天气预报"));
            }
        }
    }
    // 更新温度曲线数据
        m_tempChart->get_weather_temp(forecasts);
}


